//package com.geely.pma.climate.api.observation
package com.wanghaibo.vgashow.api.observation;


import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.annotation.RequiresApi
import com.ecarx.xui.adaptapi.car.base.ICarFunction
import com.ecarx.xui.adaptapi.car.base.ICarFunction.IFunctionValueWatcher
import com.ecarx.xui.adaptapi.vehicle.VehicleZone

/**
 * Name: CarFunctionValueObservation
 *
 * Created by Wuhao on 2020/5/19
 *
 * Version: 0.0.1
 */
class CarFunctionValueObservation(
    function: Int?, zones: IntArray?,
    watcher: IFunctionValueWatcher,
    subscription: ICarFunctionSubscription
) : CarFunctionObservation(function, zones, watcher, subscription) {

    override fun onInitialized(carFunction: ICarFunction) {
        if (function != null) {
            if (zones == null || zones.isEmpty()) {
                callerWatcher.onFunctionValueChanged(
                    function, VehicleZone.ZONE_ALL, carFunction.getFunctionValue(function)
                )
            } else {
                for (zone in zones) {
                    callerWatcher.onFunctionValueChanged(
                        function, zone, carFunction.getFunctionValue(function, zone)
                    )
                }
            }
        }
        subscription.observeFunction(carFunction, this)
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onFunctionValueChanged(function: Int, zone: Int, value: Int) {
        if (zones == null || zones.isEmpty() || contains(zones, zone)) {
            val looper = getCallLooper() ?: Looper.getMainLooper()
            synchronized(LOOPER_HANDLER_MAP) {
                val success: Boolean = LOOPER_HANDLER_MAP.computeIfAbsent(looper, ::Handler)
                    .post { callerWatcher.onFunctionValueChanged(function, zone, value) }
                if (!success) {
                    LOOPER_HANDLER_MAP.remove(looper)
                }
            }
        }
    }
}